package com.guigu.base.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guigu.base.entity.AgencyScope;
import com.guigu.base.entity.CourierScop;
import com.guigu.base.entity.GlobalUser;
import com.guigu.base.entity.dto.AgencyScopeDto;
import com.guigu.base.entity.dto.CourierScopDto;
import com.guigu.base.service.AgencyScopeService;
import com.guigu.base.service.CourierScopService;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 快递员业务范围表 前端控制器
 * </p>
 *
 * @author TaoLong
 * @since 2021-11-08
 */
@RestController
@RequestMapping("/base/pd-courier-scop")
@Api(tags = "快递员业务范围管理")
public class CourierScopController {

    @Autowired
    private CourierScopService courierScopService;

    /**
     * 获取在当前行政区域范围内的快递员
     *
     * @param areaId
     * @return
     */
    @ApiOperation("获取在当前行政区域范围内的快递员")
    @ApiImplicitParam(name = "areaId", value = "行政区域Id")
    @GetMapping("/getCourieScop/{areaId}")
    public R<List<CourierScop>> getCourieScop(@PathVariable("areaId") String areaId) {
        List<CourierScop> list = courierScopService.getCourierScopeInfo(areaId);

        return new R<>("2000", list);
    }


    @Autowired
    private AgencyScopeService agencyScopService;
    @Autowired
    private CourierScopService courierScopeService;

    /**
     * 批量保存机构业务范围
     * <p>
     * TODO 后续可能需要增加行政数据
     *
     * @param dtoList 机构业务范围信息
     * @return 返回信息
     */

    @PostMapping("/agency/batch")
    @ApiOperation("批量保存机构业务范围")
    @ApiImplicitParam(name = "dtoList", value = "机构业务集合")
    public R batchSaveAgencyScope(@RequestBody List<AgencyScopeDto> dtoList) {

        agencyScopService.batchSave(dtoList.stream().map(dto -> {
            AgencyScope scope = new AgencyScope();
            String s = getScopeToString(dto.getMutiPoints());
            scope.setMutiPoints(s);
            agencyScopService.delete("", dto.getAgencyId());
            BeanUtils.copyProperties(dto, scope);
            return scope;
        }).collect(Collectors.toList()));
        return new R(ResultCode.SUCCESS_CODE, "添加成功!", true);
    }

    /**
     * 获取范围
     *
     * @param list
     * @return
     */
    @Nullable
    private String getScopeToString(List<Map> list) {
        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {

            s = objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 删除机构业务范围信息
     *
     * @param dto 参数
     * @return 返回信息
     */
    @DeleteMapping("/agency")
    @ApiOperation("删除机构业务范围信息")
    public R deleteAgencyScope(@RequestBody AgencyScopeDto dto) {
        agencyScopService.delete(dto.getAreaId(), dto.getAgencyId());
        return new R(ResultCode.SUCCESS_CODE, "删除成功!");
    }

    /**
     * 获取机构业务范围列表
     *
     * @param areaId   行政区域id
     * @param agencyId 机构id
     * @return 机构业务范围列表
     */
    @GetMapping("/agency")
    @ApiOperation("获取机构业务范围列表")
    public R<List<AgencyScopeDto>> findAllAgencyScope(@RequestParam(name = "areaId", required = false) String areaId, @RequestParam(name = "agencyId", required = false) String agencyId, @RequestParam(name = "agencyIds", required = false) List<String> agencyIds, @RequestParam(name = "areaIds", required = false) List<String> areaIds) {
        return new R<>("2000", agencyScopService.findAll(areaId, agencyId, agencyIds, areaIds).stream().map(scope -> {

            List<Map> list = getScopeToList(scope.getMutiPoints());
            AgencyScopeDto dto = new AgencyScopeDto();
            dto.setMutiPoints(list);
            BeanUtils.copyProperties(scope, dto);
            return dto;
        }).collect(Collectors.toList()));
    }

    /**
     * 根据机构id查找机构范围数据
     *
     * @param agencyId
     * @return
     */
    @ApiOperation("根据机构id查找机构范围数据")
    @GetMapping("/findByAgencyScopeId/{agencyId}")
    public R<AgencyScopeDto> findByAgencyScopeId(@PathVariable String agencyId) {
        QueryWrapper<AgencyScope> queryWrapper = new QueryWrapper<AgencyScope>();
        queryWrapper.eq("agency_id", agencyId);
        AgencyScope scope = agencyScopService.getOne(queryWrapper);
        AgencyScopeDto agencyScopeDto = new AgencyScopeDto();
        BeanUtils.copyProperties(scope, agencyScopeDto);
        List<Map> scopeToList = getScopeToList(scope.getMutiPoints());
        agencyScopeDto.setMutiPoints(scopeToList);
        return new R<>(ResultCode.SUCCESS_CODE, agencyScopeDto);
    }

    @Nullable
    private List<Map> getScopeToList(String scope) {
        List<Map> list = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            list = objectMapper.readValue(scope, List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 批量保存快递员业务范围
     *
     * @param dtoList 快递员业务范围信息
     * @return 返回信息
     */
    @PostMapping("/courier/batch")
    @ApiOperation("批量保存快递员业务范围")
    public R batchSaveCourierScope(@RequestBody List<CourierScopDto> dtoList) {

        courierScopeService.batchSave(dtoList.stream().map(dto -> {
            courierScopeService.delete("", dto.getUserId());
            CourierScop scope = new CourierScop();
            String s = this.getScopeToString(dto.getMutiPoints());
            BeanUtils.copyProperties(dto, scope);
            scope.setMutiPoints(s);
            return scope;
        }).collect(Collectors.toList()));
        return new R(ResultCode.SUCCESS_CODE, "保存快递员业务范围成功!", true);
    }

    /**
     * 删除快递员业务范围信息
     *
     * @param dto 参数
     * @return 返回信息
     */
    @DeleteMapping("/courier")
    @ApiOperation("删除快递员业务范围信息")
    public R deleteCourierScope(@RequestBody CourierScopDto dto) {
        courierScopeService.delete(dto.getAreaId(), dto.getUserId());
        return new R(ResultCode.SUCCESS_CODE, "删除快递员业务范围成功!", true);
    }

    /**
     * 获取快递员业务范围列表
     *
     * @param areaId 行政区域id
     * @param userId 快递员id
     * @return 快递员业务范围列表
     */
    @GetMapping("/courier")
    @ApiOperation("获取快递员业务范围列表")
    public R<List<CourierScopDto>> findAllCourierScope(@RequestParam(name = "areaId", required = false) String areaId, @RequestParam(name = "userId", required = false) String userId) {
        return new R<>("2000", courierScopeService.findAll(areaId, userId).stream().map(scope -> {
            CourierScopDto dto = new CourierScopDto();
            List<Map> mapList = getScopeToList(scope.getMutiPoints());
            BeanUtils.copyProperties(scope, dto);
            dto.setMutiPoints(mapList);
            return dto;

        }).collect(Collectors.toList()));
    }

    /**
     * 根据机构Id查询它对应的快递员信息
     *
     * @param coreOrgId 机构Id
     * @return
     */
    @ApiOperation("根据机构Id查询它对应的快递员信息")
    @GetMapping("/findGlobalUserByCoreOrgId/{coreOrgId}")
    public R<List<GlobalUser>> findGlobalUserByCoreOrgId(@PathVariable("coreOrgId") String coreOrgId) {
        R<List<GlobalUser>> r = courierScopeService.findGlobalUserByCoreOrgId(coreOrgId);
        return r;
    }
}

